﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Data;
using System.IO;
using System.Web.Security;
using posttracker.Classes.Interfaces;
namespace posttracker.Classes
{
    public class Registration : IRegistration
    {
        /*
         * get User Object
         * return Text of success or fault
         */
        public MembershipCreateStatus Register(ref User user)
        {
            MembershipCreateStatus result = MembershipCreateStatus.ProviderError;
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(user);
                //string resultJson = client.UploadString(@"http://posttracker.azurewebsites.net/api/user/postuser", json);
                try
                {
                    client.BaseAddress =  WebConfigurationManager.AppSettings["apiUrl"];

                    string resultJson = client.UploadString("api/user/postuser", json);
                    
                    HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    User userResponsed = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                    if (response.IsSuccessStatusCode && userResponsed != null)
                    {
                        result = MembershipCreateStatus.Success;
                        //set new user Id 
                        user.Id = userResponsed.Id;
                    }
                    else
                    {
                        result = MembershipCreateStatus.UserRejected;
                    }
                }
                catch (WebException)
                {
                    result = MembershipCreateStatus.ProviderError;
                }
            }
            
            return result;

        }

        public void Update(User user)
        {
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user = user, id = user.Id});
              
                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                    string resultJson = client.UploadString("api/user/putuser", json);
                    
                    HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new HttpRequestException("User update fault.");

                    }
                }
                catch (WebException)
                {
                    throw new HttpRequestException("User update fault.");
                }
                
            }
        }
        public User GetUserByEmail(string email)
        {
            if (!string.IsNullOrEmpty(email))
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    //var user = new User() { Name = "user1", Password = "pass1" };
                    //var json = Newtonsoft.Json.JsonConvert.SerializeObject(user);
                    //string resultJson = client.UploadString(@"http://posttracker.azurewebsites.net/api/user/postuser", json);
                    try
                    {
                        client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];
                        //var json = Newtonsoft.Json.JsonConvert.SerializeObject(email);
                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user = new User(){ Email = email}, id = 0 });
                        string resultJson = client.UploadString("api/user/getuserbyemail/",json);
                        HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                        User userResponsed = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        if (response != null && response.IsSuccessStatusCode && userResponsed != null)
                        {
                            userResponsed.SetUserName(userResponsed.UserNameTransfered);
                            return userResponsed;
                        }
                        else
                        {
                           return null;
                        }
                    }
                    catch (WebException)
                    {

                        return null;
                    }
                }

               
               
            }
            else
            {
                throw new ArgumentException("Email can not be empty.");
            }
           
        }

        public bool DeleteUser(string name, bool deleteAllRelatedData)
        {
            if (!string.IsNullOrEmpty(name))
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    
                    try
                    {
                        client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];
                        var user = new User();
                        user.SetUserName(name);
                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user , Id = deleteAllRelatedData ? 1 : 0});
                        string resultJson = client.UploadString("api/user/deleteuser/", json);
                        HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                        User userResponsed = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        if (response.IsSuccessStatusCode && userResponsed != null)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (WebException)
                    {
                        return false;
                    }
                }
                               
            }
            else
            {
                throw new ArgumentException("Email can not be empty.");
            }

            
        }
        /*
         * get User Object
         * return True or False         
         */

        public bool ValidateUser(string name, string password)
        {
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(password))
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";

                    try
                    {
                        client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];
                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user = new User() { UserNameTransfered = name, Password = password }, Id = 0 });
                        string resultJson = client.UploadString("api/user/AuthenticateUser/", json);
                        HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                        
                        if (response != null && response.IsSuccessStatusCode)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    catch (WebException)
                    {
                        return false;
                    }
                }

            }
            else
            {
                throw new ArgumentException("Parametrs can not be empty.");
            }
        }


        public User GetUser(int id, bool updateLastActivityDate)
        {
            if (id > 0)
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                   
                    try
                    {
                        client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];
                        //var json = Newtonsoft.Json.JsonConvert.SerializeObject(email);
                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user = new User() { Id = id }, id = updateLastActivityDate ? 1 : 0 });
                        string resultJson = client.UploadString("api/user/getuser/", json);
                        HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                        User userResponsed = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        if (response.IsSuccessStatusCode && userResponsed != null)
                        {

                            return userResponsed;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (WebException)
                    {
                        return null;
                    }
                }
            }
            else
            {
                throw new ArgumentException("Email can not be empty.");
            }


        }

        public User GetUser(string name, bool updateLastActivityDate)
        {
            if (!string.IsNullOrEmpty(name))
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";

                    try
                    {
                        client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];
                  
                        var user = new User();
                        user.SetUserName(name);
                        //prepare json
                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user, id = updateLastActivityDate ? 1 : 0 });
                        //get result 
                        string resultJson = client.UploadString("api/user/getuser/", json);
                        HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                        User userResponsed = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        if (response.IsSuccessStatusCode && userResponsed != null)
                        {
                            return userResponsed;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (WebException)
                    {

                        return null;
                    }
                }
            }
            else
            {
                throw new ArgumentException("Email can not be empty.");
            }


        }

        public MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                    MembershipUserCollection users = new MembershipUserCollection();
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { pageIndex = pageIndex, pageSize = pageSize});
                    //get result 
                    string resultJson = client.UploadString("api/user/getallusers/", json);
                    //HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    //IEnumerable<User> usersList = (IEnumerable<User>)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(IEnumerable<User>));
                    PutUserRequestCollection response = (PutUserRequestCollection)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(PutUserRequestCollection));
                    totalRecords = 0;
                    if (
                        //response.IsSuccessStatusCode && 
                        response.userCollection != null)
                    {
                        IEnumerable<User> usersList = response.userCollection;
                        totalRecords = response.count;

                        foreach (MembershipUser user in usersList)
                        {
                            ((User)user).SetUserName(((User)user).UserNameTransfered);
                            users.Add(user);
                        }
                        
                    }

                    return users;
                    
                }
                catch (WebException)
                {
                    throw new WebException("Error on user request.");
                }
            }

        }

        public int GetNumberOfUsersOnline(DateTime timeFrom)
        {
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                  
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new RequestCollection() { datetime = timeFrom });
                    //get result 
                    string resultJson = client.UploadString("api/user/getnumberofusersonline/", json);
                                       
                    int usersOnline = (int)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(int));
                    return usersOnline;
                    

                    

                }
                catch (WebException)
                {
                    return 0;
                }
            }

      
        }

        public string GetPassword(string name)
        {
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                    var user = new User();
                    user.SetUserName(name);
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user, id = 0 });
                    //get result 
                    string resultJson = client.UploadString("api/user/getpassword/", json);
                    HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    

                    if (response.IsSuccessStatusCode)
                    {
                        User password = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        return password.Password;
                    }



                }
                catch (WebException)
                {
                    throw new WebException("Error on user request.");
                }
            }

            return String.Empty;
        }

        public bool ChangePassword(string name, string oldPassword, string newPassword)
        {
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                    var user = new User();
                    user.SetUserName(oldPassword);
                    user.Password = newPassword;
                    user.Email = name;
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user, id = 0 });
                    //get result 
                    string resultJson = client.UploadString("api/user/changepassword/", json);
                    HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    
                    if (response.IsSuccessStatusCode)
                    {
                        User password = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        return true;
                    }



                }
                catch (WebException)
                {
                    return false;
                }
            }

            return false;
        }

        public MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {

            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                MembershipUserCollection users = new MembershipUserCollection();
                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                    
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { searchParam = usernameToMatch, pageIndex = pageIndex, pageSize = pageSize });
                    //get result 
                    string resultJson = client.UploadString("api/user/findusersbyname/", json);
                    //HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    PutUserRequestCollection response = (PutUserRequestCollection)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(PutUserRequestCollection));
                    totalRecords = 0;
                    if (
                        //response.IsSuccessStatusCode && 
                        response.userCollection != null)
                    {
                        IEnumerable<User> usersList = response.userCollection;
                        totalRecords = response.count;

                        foreach (MembershipUser user in usersList)
                        {
                            ((User)user).SetUserName(((User)user).UserNameTransfered);
                            users.Add(user);
                        }

                    }

                    return users;

                }
                catch (WebException)
                {
                    totalRecords = 0;
                    return users;
                }
            }

        }


        public MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {

            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                MembershipUserCollection users = new MembershipUserCollection();
                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

                    
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { searchParam = emailToMatch, pageIndex = pageIndex, pageSize = pageSize });
                    //get result 
                    string resultJson = client.UploadString("api/user/findusersbyemail/", json);
                    //HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                    PutUserRequestCollection response = (PutUserRequestCollection)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(PutUserRequestCollection));
                    totalRecords = 0;
                    if (
                        //response.IsSuccessStatusCode && 
                        response.userCollection != null)
                    {
                        IEnumerable<User> usersList = response.userCollection;
                        totalRecords = response.count;

                        foreach (MembershipUser user in usersList)
                        {
                            ((User)user).SetUserName(((User)user).UserNameTransfered);
                            users.Add(user);
                        }

                    }

                    return users;

                }
                catch (WebException)
                {
                    totalRecords = 0;
                    return users;
                }
            }

        }

        public bool UnlockUser(string name)
        {

            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";

                try
                {
                    client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];


                    var user = new User();
                    user.SetUserName(name);
                   
                    //prepare json
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user, id = 0 });
                    //get result 
                    string resultJson = client.UploadString("api/user/unlockuser/", json);
                    HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
                   // string password = (string)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(string));

                    if (response.IsSuccessStatusCode)
                    {
                        //User userComming = (User)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(User));
                        return true;
                    }



                }
                catch (WebException)
                {
                    return false;
                }
            }

            return false;
        }

        //public static void Update(User user, int i )
        //{
            
        //    using (var client = new WebClient())
        //    {
        //        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        //        var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { user = user, id = user.Id });

        //        try
        //        {
        //            client.BaseAddress = WebConfigurationManager.AppSettings["apiUrl"];

        //            string resultJson = client.UploadString("api/user/putuser", json);

        //            HttpResponseMessage response = (HttpResponseMessage)Newtonsoft.Json.JsonConvert.DeserializeObject(resultJson, typeof(HttpResponseMessage));
        //            if (!response.IsSuccessStatusCode)
        //            {
        //                throw new HttpRequestException("User update fault.");

        //            }
        //        }
        //        catch (WebException)
        //        {
        //            throw new HttpRequestException("User update fault.");
        //        }

        //    }
        //}
    }
}